import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { UserInput, GeneratedName } from '@/utils/nameGenerator';
import { generateNames } from '@/utils/nameGenerator';

export const useNameStore = defineStore('name', () => {
  // 状态
  const userInput = ref<UserInput>({
    birthDate: '',
    timePeriod: '',
    gender: '男孩',
    surname: ''
  });

  const generatedNames = ref<GeneratedName[]>([]);
  const savedNames = ref<GeneratedName[]>([]);
  const isLoading = ref(false);

  // 计算属性
  const hasValidInput = computed(() => {
    return userInput.value.birthDate && 
           userInput.value.surname && 
           userInput.value.gender;
  });

  // 动作
  const updateUserInput = (input: Partial<UserInput>) => {
    // 直接更新对应的字段
    if (input.birthDate !== undefined) userInput.value.birthDate = input.birthDate;
    if (input.timePeriod !== undefined) userInput.value.timePeriod = input.timePeriod;
    if (input.gender !== undefined) userInput.value.gender = input.gender;
    if (input.surname !== undefined) userInput.value.surname = input.surname;
  };

  const generateNameSuggestions = async () => {
    console.log('开始生成名字，用户输入:', userInput.value);
    console.log('输入是否有效:', hasValidInput.value);
    
    if (!hasValidInput.value) {
      console.log('输入无效，退出生成');
      return;
    }

    isLoading.value = true;
    try {
      console.log('等待1秒...');
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      console.log('调用generateNames函数...');
      const names = generateNames(userInput.value, 3);
      console.log('生成的名字:', names);
      
      generatedNames.value = names;
      console.log('更新generatedNames:', generatedNames.value);
    } catch (error) {
      console.error('生成名字失败:', error);
      generatedNames.value = [];
    } finally {
      isLoading.value = false;
      console.log('生成完成，isLoading设为false');
    }
  };

  const saveName = (name: GeneratedName) => {
    const exists = savedNames.value.some(saved => saved.fullName === name.fullName);
    if (!exists) {
      savedNames.value.push(name);
    }
  };

  const removeSavedName = (name: GeneratedName) => {
    const index = savedNames.value.findIndex(saved => saved.fullName === name.fullName);
    if (index > -1) {
      savedNames.value.splice(index, 1);
    }
  };

  return {
    userInput,
    generatedNames,
    savedNames,
    isLoading,
    hasValidInput,
    updateUserInput,
    generateNameSuggestions,
    saveName,
    removeSavedName
  };
}); 